﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Media;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;



namespace BitPortal.Utils
{
    public static class ImageUtils
    {
        /// <summary>
        /// Download anh : truyen vao duong dan, tra ve doi tuong Image
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static System.Drawing.Image DownloadImage(string Url)
        {
            System.Drawing.Image _tmpImage = null;

            try
            {
                // Open a connection
                System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(Url);

                _HttpWebRequest.AllowWriteStreamBuffering = true;

                // You can also specify additional header values like the user agent or the referer: (Optional)
                _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
                _HttpWebRequest.Referer = "http://www.google.com/";

                // set timeout for 20 seconds (Optional)
                _HttpWebRequest.Timeout = 20000;

                // Request response:
                System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();

                // Open data stream:
                System.IO.Stream _WebStream = _WebResponse.GetResponseStream();

                // convert webstream to image
                _tmpImage = System.Drawing.Image.FromStream(_WebStream);

                // Cleanup
                _WebResponse.Close();
                _WebResponse.Close();
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
                return null;
            }

            return _tmpImage;
        }
        /// <summary>
        /// Luu anh tu internet, tra ve duong dan tuyet doi cua anh.
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="TargetFolder"></param>
        /// <returns></returns>
        public static string SaveImage(string Url, string TargetFolder = "~/Upload/Image")
        {
            try
            {
                System.Drawing.Image img = DownloadImage(Url);
                if (img != null)
                {
                    string filename = Url.Split(new Char[] { '/' }).Last().Replace(" ", "");
                    img.Save(HttpContext.Current.Server.MapPath(TargetFolder) + "/" + filename);
                    return TargetFolder.Substring(1) + "/" + filename;
                }
            }
            catch { }
            return null;
        }
    }
}
